package com.lq.gulimall.product.service.impl;

import com.lq.gulimall.product.constant.ProductConstant;
import com.lq.gulimall.product.dao.PmsAttrAttrgroupRelationDao;
import com.lq.gulimall.product.dao.PmsAttrGroupDao;
import com.lq.gulimall.product.dao.PmsCategoryDao;
import com.lq.gulimall.product.entity.PmsAttrAttrgroupRelationEntity;
import com.lq.gulimall.product.entity.PmsAttrGroupEntity;
import com.lq.gulimall.product.entity.PmsCategoryEntity;
import com.lq.gulimall.product.service.PmsAttrAttrgroupRelationService;
import com.lq.gulimall.product.service.PmsCategoryService;
import com.lq.gulimall.product.vo.Attr;
import com.lq.gulimall.product.vo.AttrGroupRelationVo;
import com.lq.gulimall.product.vo.AttrReadVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import com.lq.gulimall.product.dao.PmsAttrDao;
import com.lq.gulimall.product.entity.PmsAttrEntity;
import com.lq.gulimall.product.service.PmsAttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("pmsAttrService")
public class PmsAttrServiceImpl extends ServiceImpl<PmsAttrDao, PmsAttrEntity> implements PmsAttrService {
    @Autowired
    private PmsAttrAttrgroupRelationDao attrgroupRelationDao;
    @Autowired
    private PmsAttrGroupDao attrGroupDao;
    @Autowired
    private PmsCategoryDao categoryDao;
    @Autowired
    private PmsCategoryService categoryService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PmsAttrEntity> page = this.page(
                new Query<PmsAttrEntity>().getPage(params),
                new QueryWrapper<PmsAttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional //事务
    @Override
    public void saveAttr(Attr attr) {
        PmsAttrEntity attrEntity = new PmsAttrEntity();
        //属性拷贝
        BeanUtils.copyProperties(attr, attrEntity);
        //保存数据
        this.save(attrEntity);
        //保存关联关系
        if(attr.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()&&attr.getAttrGroupId()!=null){
            PmsAttrAttrgroupRelationEntity relationEntity = new PmsAttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());
            attrgroupRelationDao.insert(relationEntity);
        }
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catId,String type) {
        QueryWrapper<PmsAttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_type","base".equalsIgnoreCase(type)? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():
                ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode() );
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((obj) -> {
                obj.eq("attr_id", key)
                        .or().like("attr_name", key);
            });
        }
        IPage<PmsAttrEntity> page = this.page(
                new Query<PmsAttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<PmsAttrEntity> records = page.getRecords();
        List<AttrReadVo> voList = records.stream().map(attr -> {
            AttrReadVo attrReadVo = new AttrReadVo();
            BeanUtils.copyProperties(attr, attrReadVo);
            //设置分类
            if ("base".equalsIgnoreCase(type)) {
                PmsAttrAttrgroupRelationEntity attr_id = attrgroupRelationDao.selectOne(new QueryWrapper<PmsAttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
                if (attr_id != null&&attr_id.getAttrGroupId()!=null) {
                    PmsAttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attr_id);
                    attrReadVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }

            //设置分组
            PmsCategoryEntity categoryEntity = categoryDao.selectById(attr.getCatelogId());
            if (categoryEntity != null) {
                attrReadVo.setCatelogName(categoryEntity.getName());
            }


            return attrReadVo;
        }).collect(Collectors.toList());
        pageUtils.setList(voList);
        return pageUtils;
    }

    /**
     * 详情查询
     *
     * @param attrId
     * @return
     */
    @Override
    public AttrReadVo getAttrInfo(Long attrId) {
        AttrReadVo attrReadVo = new AttrReadVo();
        PmsAttrEntity pmsAttrEntity = this.getById(attrId);
        BeanUtils.copyProperties(pmsAttrEntity, attrReadVo);
        //设置分组
        if(attrReadVo.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            PmsAttrAttrgroupRelationEntity relationEntity = attrgroupRelationDao.selectOne(new QueryWrapper<PmsAttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (relationEntity != null) {
                attrReadVo.setAttrGroupId(relationEntity.getAttrGroupId());

                PmsAttrGroupEntity groupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if (groupEntity != null) {
                    attrReadVo.setGroupName(groupEntity.getAttrGroupName());
                }
            }
        }

        //设置分类信息
        Long catelogId = pmsAttrEntity.getCatelogId();
        //查询出全部的路径
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        attrReadVo.setCatelogPath(catelogPath);
        PmsCategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (categoryEntity != null) {
            attrReadVo.setCatelogName(categoryEntity.getName());
        }

        return attrReadVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrReadVo pmsAttr) {
        PmsAttrEntity attrEntity = new PmsAttrEntity();
        BeanUtils.copyProperties(pmsAttr, attrEntity);
        updateById(attrEntity);
        if(attrEntity.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            //修改分组关联
            PmsAttrAttrgroupRelationEntity atrrAtrr = new PmsAttrAttrgroupRelationEntity();
            atrrAtrr.setAttrGroupId(pmsAttr.getAttrId());
            Integer count = attrgroupRelationDao.selectCount(new QueryWrapper<PmsAttrAttrgroupRelationEntity>().eq("attr_id", atrrAtrr.getAttrId()));
            if (count > 0) {
                attrgroupRelationDao.update(atrrAtrr, new QueryWrapper<PmsAttrAttrgroupRelationEntity>().eq("attr_id", atrrAtrr.getAttrId()));

            } else {
                attrgroupRelationDao.insert(atrrAtrr);
            }
        }

        this.update();
    }

    /**
     * 根据分组id查询关联的所有基本属性
     * @param attrgroupId
     * @return
     */
    @Override
    public List<PmsAttrEntity> getRlationAttr(Long attrgroupId) {
        List<PmsAttrAttrgroupRelationEntity> relationg = attrgroupRelationDao.selectList(
                new QueryWrapper<PmsAttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        List<Long> ids = relationg.stream().map((atrtr) -> {
            return atrtr.getAttrId();
        }).collect(Collectors.toList());
        if(ids.size()<1){
            return null;
        }
        Collection<PmsAttrEntity> entities = this.listByIds(ids);
        return (List<PmsAttrEntity>)entities;
    }

    /**
     *  删除关联
     * @param relationVos
     */
    @Override
    public void deleteRelation(AttrGroupRelationVo[] relationVos) {
        List<PmsAttrAttrgroupRelationEntity> relationEntities = Arrays.asList(relationVos).stream().map((item) -> {
            PmsAttrAttrgroupRelationEntity relationEntity = new PmsAttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
            attrgroupRelationDao.deleteBatchRelation(relationEntities);
    }

    /**
     * 获取当前分组没有关联的所有属性
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        // 当前分组只能关联自己所属的分类里面所有属性
        PmsAttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        //当前分组只能关联别的复制没有引用的属性
        //当前分类下的其他分组
        List<PmsAttrGroupEntity> groupEntityList = attrGroupDao.selectList(new QueryWrapper<PmsAttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> longList = groupEntityList.stream().map((iter) -> {
            return iter.getAttrGroupId();
        }).collect(Collectors.toList());
        //这些分组关联的属性
        List<PmsAttrAttrgroupRelationEntity> groupId = attrgroupRelationDao.selectList(
                new QueryWrapper<PmsAttrAttrgroupRelationEntity>().in("attr_group_id", longList));
        List<Long> attrids = groupId.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        //从当前分类的所有属性中移除这些属性
        QueryWrapper<PmsAttrEntity> wrapper = new QueryWrapper<PmsAttrEntity>().eq("catelog_id", catelogId).eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if(attrids.size()>0){
            wrapper.notIn("attr_id", attrids);
        }
        String key= (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
             wrapper.and((w)->{
                 w.eq("attr_id",key).or().like("attr_name",key);
                 });
        }
        IPage<PmsAttrEntity> page = this.page(new Query<PmsAttrEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }


}